<template>
  <div class="cl-box">
    <el-select v-model="currZd" style="width: 98%;" value-key="zdmc" @change="handleZdChange">
      <el-option v-for="zd in zdList" :key="zd.zdmc" :label="zd.zdzwmc" :value="zd"/>
    </el-select>
    <el-input v-model="search" clearable placeholder="关键字" style="margin-top: 5px"/>
    <div class="tree-box">
      <!--<my-tree ref="myTree" :data="clList" :filter-node-method="filterNode" :props="props"-->
      <!--         @item-click="handleItemClick"-->
      <!--         @item-contextmenu="showContextmenu"/>-->
      <el-tree
          ref="myTree"
          :data="clList"
          :filter-node-method="filterNode"
          :props=" props"
          class="myTree"
          @node-contextmenu="showContextmenu"
          @node-click="handleItemClick"></el-tree>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import MyTree from "@/components/MyTree";

let reg = /[A-Za-z_]+\.[A-Za-z_]+/g

function getZdmcList (bds) {
  if (!bds) return []
  let arr = bds.match(reg)
  if (!arr) return []
  return arr.map(item => item)
}

export default {
  components: { MyTree },
  name: "SelectCl",
  props: {
    bds: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      currZd: {},
      zdList: [],

      clList: [],
      props: {
        id: "dm",
        label: 'mc',
      },
      search: ''
    }
  },
  computed: {
    ...mapState(['stTreeObj'])
  },
  async mounted () {
    let zdmcList = getZdmcList(this.bds)
    let zdList = []
    for (let zdmc of zdmcList) {
      if (zdList.find(item => item.zdmc === zdmc)) continue;
      let stjg = this.stTreeObj[zdmc]
      if (!stjg || !stjg.sjybm) continue;
      zdList.push(stjg)
    }
    if (zdList.length) {
      this.currZd = zdList[0]
      this.handleZdChange()
    }
    this.zdList = zdList;
  },
  watch: {
    search () {
      this.$refs.myTree.filter(this.search)
    }
  },
  methods: {
    filterNode (value, data) {
      if (!value) return true;
      return data[this.props.label].indexOf(value) !== -1;
    },
    async handleZdChange () {
      let res = await this.$api.getSjysj({
        sjydz: this.currZd.sjydz,
        glcs: this.currZd.glcs
      })
      this.clList = this.$listToTree(res, 'dm', 'fdm');
    },
    handleItemClick (cl) {
      this.$emit('select', cl)
    },
    showContextmenu (e, cl) {
      this.$contextmenu([
        {
          label: "插入所有子级",
          show: true,
          click: () => {
            console.log(cl)
            this.$emit('select-children', cl.children)
          }
        }])
    }
  }
}
</script>

<style lang="scss" scoped>
.cl-box {
  height: 100%;
  display: flex;
  flex-direction: column;

  .tree-box {
    flex: 1;
    overflow-y: auto;
  }
}
</style>
